package com.sav.common.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Component;

import com.sav.common.catalog.Cart;
import com.sav.common.catalog.Product;
import com.sav.common.containers.ProductContainer;


@Component
public class CartDAO extends BaseDAO {
	
	//@Autowired(required = true)
    private ProductDAO productDAO = new ProductDAO();
	
	public CartDAO() {
	}
	
	
	public void saveCart(Cart cart) {
		PreparedStatement stm = null;
		int summ = 0; 
		int idOrder = 0;
		
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String query = "INSERT INTO orders(idUser, dateOrder, totalCost) VALUES(?, ?, ?)";
			stm = createStatementForInsert(query);
			stm.setInt(1, cart.getIdUser());
			stm.setString(2, dateFormat.format(new Date()));
			stm.setInt(3, 0);
			idOrder = executeInsert(stm);
			/*stm = getConnection().prepareStatement(query);
			stm.setInt(1, cart.getIdUser());
			stm.setString(2, dateFormat.format(new Date()));
			stm.setInt(3, 0);
			stm.executeUpdate();
			
			Statement statement = getConnection().createStatement();
			ResultSet resultSet = statement.executeQuery(""
					+ "SELECT MAX(idOrder) as id FROM orders");
			resultSet.next();
			idOrder = resultSet.getInt("id"); */
			
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		
		for (ProductContainer l : cart.getListProducts()) {
			Product product = productDAO.getProductById(l.getIdProduct());
			summ += product.getCost()*l.getNumber();
			
			try {
				String query = "INSERT INTO cart(idOrder, idProduct, cost, numberProducts) VALUES(?, ?, ?, ?)";
				stm = getConnection().prepareStatement(query);
				stm.setInt(1, idOrder);
				stm.setInt(2, l.getIdProduct());
				stm.setInt(3, product.getCost());
				stm.setInt(4, l.getNumber());
				stm.executeUpdate();
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
			finally {
				try {
					stm.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		try {
			String query = "UPDATE orders SET totalCost = ? ";
			stm = getConnection().prepareStatement(query);
			stm.setInt(1, summ);
			stm.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		
		
	}
}
